package com.zjs.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjs.common.lang.Result;
import com.zjs.dao.dos.Archives;
import com.zjs.dao.entity.Article;

import com.zjs.dao.entity.ArticleBody;
import com.zjs.dao.entity.ArticleTag;
import com.zjs.dao.entity.SysUser;
import com.zjs.dao.vo.ArticleBodyVo;
import com.zjs.dao.vo.ArticleVo;
import com.zjs.dao.vo.TagVo;
import com.zjs.dao.vo.params.ArticleParam;
import com.zjs.dao.vo.params.PageParams;
import com.zjs.mapper.ArticleBodyMapper;
import com.zjs.mapper.ArticleMapper;
import com.zjs.mapper.ArticleTagMapper;
import com.zjs.mapper.TagMapper;
import com.zjs.service.ArticleService;

import com.zjs.service.CategoryService;
import com.zjs.service.SysUserService;
import com.zjs.service.TagService;
import com.zjs.utils.UserThreadLocal;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 关注公众号：MarkerHub
 * @since 2022-02-22
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private TagService tagService;

    @Autowired
    private ArticleTagMapper articleTagMapper;




    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor, boolean isBody,boolean isCategory) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTag,isAuthor,isBody,isCategory));
        }
        return articleVoList;
    }

    /**
     * 复制列表
     * @param records 文章列表
     * @param isAuthor 是否需要作者信息
     * @param isTags 是否需要标签
     * @return
     */
    private List<ArticleVo> copyList(List<Article> records, boolean isAuthor,  boolean isTags) {
        //创建一个vo-list，边遍历原、边赋值
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTags,isAuthor,false,false));;
        }
        return articleVoList;
    }

    /**
     *
     * @param article 文章
     * @param isAuthor 是否需要作者信息
     * @param isBody 是否需要内容
     * @param isTag 是否需要标签
     * @param isCategory 是否需要类别
     * @return
     */
    private ArticleVo copy(Article article, boolean isTag, boolean isAuthor, boolean isBody,boolean isCategory){
        //创建文章vo
        ArticleVo articleVo = new ArticleVo();
        //缓存json转换导致的精度损失
        //dao=>vo
        articleVo.setId(String.valueOf(article.getId()));
        BeanUtils.copyProperties(article,articleVo);
        //设置文章创建时间 时间戳=>文本
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        //并不是所有的接口 都需要标签 ，作者信息
        if (isTag){
            Long articleId = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        if (isAuthor){
            //获取作者名字
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        //获取内容
        if (isBody){
            Long bodyId = article.getBodyId();
            articleVo.setBody(findArticleBodyById(bodyId));
        }
        //获取类别
        if (isCategory){
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(categoryId));
        }
        return articleVo;
    }

    /**
     * 分页查询 文章列表
     * @param pageParams
     * @return
     */
    @Override
    public Result listArticlesPage(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(),pageParams.getPageSize());

        IPage<Article> articleIPage = articleMapper.listArticle(
                page,
                pageParams.getCategoryId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth());
        List<Article> records = articleIPage.getRecords();
        return Result.success(copyList(records,true,true));
    }
    //@Override
    //public Result listArticlesPage(PageParams pageParams) {
    //    /**
    //     * 1. 分页查询 article数据库表
    //     */
    //    Page<Article> page = new Page<>(pageParams.getPage(),pageParams.getPageSize());
    //    LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
    //    //1. 根据类别
    //    if (pageParams.getCategoryId() != null){
    //        // and category_id=#{categoryId}
    //        queryWrapper.eq(Article::getCategoryId,pageParams.getCategoryId());
    //    }
    //    List<Long> articleIdList = new ArrayList<>();
    //    //2. 根据标签
    //    if (pageParams.getTagId() != null){
    //        //加入标签 条件查询
    //        //article表中 并没有tag字段 一篇文章 有多个标签
    //        //article_tag  article_id 1 : n tag_id
    //        LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
    //        //  根据TagId去关联表里查询 文章id
    //        articleTagLambdaQueryWrapper.eq(ArticleTag::getTagId,pageParams.getTagId());
    //        List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagLambdaQueryWrapper);
    //        for (ArticleTag articleTag : articleTags) {
    //            articleIdList.add(articleTag.getArticleId());
    //        }
    //        //  根据文章id构建条件
    //        if (articleIdList.size() > 0){
    //            //2.1  and id in(1,2,3)
    //            queryWrapper.in(Article::getId,articleIdList);
    //        }
    //    }
    //    //是否置顶进行排序
    //    //3. order by create_date desc
    //    queryWrapper.orderByDesc(Article::getWeight,Article::getCreateDate);
    //    //4. 查询
    //    IPage<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
    //    List<Article> records = articlePage.getRecords();
    //    //5.添加1作者和标签名
    //    List<ArticleVo> articleVoList = copyList(records,true,true);
    //    return Result.success(articleVoList);
    //}

    /**
     * 最热文章
     * @param limit
     * @return
     */
    @Override
    public Result hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //倒叙
        queryWrapper.orderByDesc(Article::getViewCounts);
        //只取两条数据
        queryWrapper.select(Article::getId,Article::getTitle);
        //limit注意空格
        queryWrapper.last("limit "+limit);
        //select id,title from article order by view_counts desc limit 5
        List<Article> articles = articleMapper.selectList(queryWrapper);

        return Result.success(articles);
    }

    @Override
    public Result newArticles(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //根据时间倒序
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.select(Article::getId,Article::getTitle);
        queryWrapper.last("limit "+limit);
        //select id,title from article order by create_date desc desc limit 5
        List<Article> articles = articleMapper.selectList(queryWrapper);

        return Result.success(articles);
    }

    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);
    }

    @Autowired
    private ThreadService threadService;
    /**
     * 根据id查询文章+详情
     */

    @Override
    public Result findArticleById(Long articleId) {
        /**
         * 1. 根据id查询 文章信息
         * 2. 根据bodyId和categoryid 去做关联查询
         */
        Article article = this.articleMapper.selectById(articleId);
        ArticleVo articleVo = copy(article, true, true,true,true);
/*        查看完文章了，新增阅读数，有没有问题呢？
        查看完文章之后，本应该直接返回数据了，这时候做了一个更新操作，更新时加写锁，阻塞其他的读操作，性能就会比较低
        更新 增加了此次接口的 耗时 如果一旦更新出问题，不能影响 查看文章的操作
        线程池  可以把更新操作 扔到线程池中去执行，和主线程就不相关了*/
        //                                     mapper      数据
        threadService.updateArticleViewCount(articleMapper,article);
        return Result.success(articleVo);
    }

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ArticleBodyMapper articleBodyMapper;
    /**
     * 根据id查询描述
     * @param bodyId
     * @return
     */
    private ArticleBodyVo findArticleBodyById(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }

    @Override
    public Result publish(ArticleParam articleParam) {
        //此接口 要加入到登录拦截当中
        SysUser sysUser = UserThreadLocal.get();
        /**
         * 1. 发布文章 目的 构建Article对象
         * 2. 作者id  当前的登录用户
         * 3. 标签  要将标签加入到 关联列表当中
         * 4. body 内容存储 article bodyId
         */
        Article article = new Article();
        article.setAuthorId(sysUser.getId());
        article.setWeight(Article.Article_Common);
        article.setViewCounts(0);
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCommentCounts(0);
        article.setCreateDate(System.currentTimeMillis());

        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));
        //插入之后 会生成一个文章id
        this.articleMapper.insert(article);
        //tag
        List<TagVo> tags = articleParam.getTags();
        //    循环遍历tags插入
        if (tags != null){
            for (TagVo tag : tags) {
                Long articleId = article.getId();
                ArticleTag articleTag = new ArticleTag();
                //缓存json转换导致的精度损失
                //vo=>dao
                articleTag.setTagId(Long.parseLong(tag.getId()));
                articleTag.setArticleId(articleId);
                articleTagMapper.insert(articleTag);
            }
        }
        //body

        ArticleBody articleBody  = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);
            //插入body后获取id加入文章
        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
        Map<String,String> map = new HashMap<>();
        map.put("id",article.getId().toString());
        return Result.success(map);
    }


}
